package com.hujia.hjsurprisemeal.service;

import com.hujia.hjsurprisemeal.model.Order;
import com.hujia.hjsurprisemeal.model.User;
import com.hujia.hjsurprisemeal.repository.OrderMapper;
import com.hujia.hjsurprisemeal.repository.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishService dishService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PricingService pricingService;

    /**
     * 使用@Transactional注解确保方法内的数据库操作在同一个事务中执行。
     * 如果方法中抛出运行时异常，则事务将回滚。
     */
    @Transactional
    public Order placeOrder(Integer userId, List<Integer> dishIds) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证餐品库存是否充足并扣除库存
        List<Integer> validDishIds = dishIds.stream()
                .filter(dishService::checkInventory)
                .collect(Collectors.toList());
        if (validDishIds.size() != dishIds.size()) {
            throw new RuntimeException("部分餐品库存不足");
        }
        validDishIds.forEach(dishService::decrementInventory);

        // 计算订单总金额
        Double totalAmount = validDishIds.stream()
                .mapToDouble(dishId -> pricingService.getPrice(dishId))
                .sum();

        // 创建订单记录
        Order order = new Order();
        order.setUserId(userId);
        order.setDishIds(validDishIds);
        order.setTotalAmount(totalAmount);
        order.setOrderTime(LocalDateTime.now());
        orderMapper.insert(order);

        return order;
    }
}